<template>
  <SelectTable
    v-if="isEdit"
    v-model:value="medicineInfo.mc"
    :type="type"
    :search-params="searchParams"
    :auto-focus="autoFocus || isOpen"
    :table-width="tableWidth"
    @close="onClose"
    @select="onSelectMedicine"
  />
  <div v-else class="w-full h-full flex items-center cell-style" @click="onClick">
    <div v-if="medicineInfo?.mc" class="truncate mr-2" :title="medicineInfo?.mc">{{ medicineInfo?.mc }}</div>
    <div v-if="medicineInfo?.gg" class="text-gray-400 mr-2 text-xs truncate" :title="medicineInfo?.gg">{{ medicineInfo?.gg }}</div>
    <div v-if="medicineInfo?.cj" class="text-gray-400 mr-2 text-xs max-w-[64px] truncate" :title="medicineInfo?.cj">{{ medicineInfo?.cj }}</div>
    <a-button
      v-if="insureStatus !== 1 && (medicineInfo?.insureStatus !== 1 || medicineInfo?.insureStatus === undefined)"
      type="primary"
      shape="circle"
      size="small"
      class="bg-orange-400"
      >自</a-button
    >
    <a-button v-if="rowData.skinTestFlag === 1 || value.skinTestFlag === 1" type="primary" shape="circle" size="small" class="bg-red-500 ml-1">皮</a-button>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import SelectTable from '@/components/SelectTable'

const isOpen = ref(false)
const isEdit = ref(true)
const medicineInfo = ref({
  mc: '',
  gg: '',
  cj: ''
})
const emit = defineEmits(['select'])
const props = defineProps({
  value: {
    type: Object,
    default: () => ({ mc: '', gg: '', cj: '' })
  },
  rowData: {
    type: Object,
    default: () => ({})
  },
  searchParams: {
    type: Object,
    default: () => ({})
  },
  type: {
    type: String,
    default: '处方'
  },
  autoFocus: {
    type: Boolean,
    default: false
  },
  insureStatus: {
    type: Number,
    default: 1
  },
  tableWidth: {
    type: Number,
    default: 720
  },
  isVerifySelect: {
    type: Boolean,
    default: false
  }
})
onMounted(() => {
  medicineInfo.value = props.value
  props.value.mc && (isEdit.value = false)
})

const onClick = () => {
  isEdit.value = true
  isOpen.value = true
}
const onClose = () => {
  isEdit.value = !medicineInfo.value?.mc
}
const onSelectMedicine = async (row) => {
  if (props.isVerifySelect) {
    const result = await new Promise((resolve) => {
      row.resolve = resolve
      emit('select', row)
    })
    if (result) {
      medicineInfo.value = row
      setTimeout(() => {
        isEdit.value = false
      }, 100)
    } else {
      medicineInfo.value = {}
    }
  } else {
    emit('select', row)
    medicineInfo.value = row
    setTimeout(() => {
      isEdit.value = false
    }, 100)
  }
}

watch(
  () => props.value.mc,
  (val) => {
    if (!val) medicineInfo.value = {}
    if (val) medicineInfo.value = props.value
  }
)
</script>
<style lang="less" scoped>
.cell-style {
  padding: 4px 11px;
  padding-top: 6px;
  border: 1px solid transparent;
  &:hover {
    border: 1px solid var(--primary-color);
  }
}
</style>
